<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <input type="text" id="message" placeholder="请输入消息">
        <button id="sendBtn" onclick="sendMessage()">发送</button>
    </div>
    <div id="app">

    </div>
    <script>
        let chat = document.getElementById('app');

        let message = document.getElementById('message');


            // 创建sse
            const eventSource = new EventSource('http://localhost:8080/subscribe?userId=0001');
            // 连接成功
            eventSource.onopen = function (event){
                console.log('sse连接成功');
            }
            // 连接失败
            eventSource.onerror = function (event){
                console.log('sse连接失败');
            }

            eventSource.onmessage = function (event){
                if (event.data){
                    chat.innerHTML += event.data + '<br>';
                }
            }



        function sendMessage(){
                console.log('发送消息');
            let messageText = message.value;
        console.log(messageText);
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'http://localhost:8080/publish?userId=0001&message='+messageText, true);
            xhr.onload = function (event){
                if (xhr.status === 200){
                    console.log('消息发送成功');
                }else {
                    console.log('消息发送失败');
                }
            }
            xhr.send();
        }

    </script>
</body>
</html>